package com.example.musicbox.service.impl;

import com.example.musicbox.config.MyException;
import com.example.musicbox.entity.MComment;
import com.example.musicbox.entity.MUser;
import com.example.musicbox.enums.AboutMusic;
import com.example.musicbox.enums.LogDoType;
import com.example.musicbox.mapper.MCommentMapper;
import com.example.musicbox.mapper.MUserMapper;
import com.example.musicbox.service.MCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.musicbox.utils.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 帅哥是我
 * @since 2022-08-03
 */
@Service
public class MCommentServiceImpl extends ServiceImpl<MCommentMapper, MComment> implements MCommentService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private MCommentMapper mCommentMapper;

    @Resource
    private MUserMapper mUserMapper;

    @Resource
    private MLogServiceImpl mLogService;

    @Override
    public Result addComment(MComment comment, String token) {
        try {
            Integer uId = (Integer) redisTemplate.opsForValue().get(token);
            MUser mUser = mUserMapper.selectById(uId);
            comment.setUid(uId);
            comment.setUphoto(mUser.getUphoto());
            comment.setUname(mUser.getUsername());
            mCommentMapper.insert(comment);
            mLogService.insertLog("用户对音乐作了评价", AboutMusic.COMMENTMUSIC, comment.getMid(), LogDoType.INSERT, token);
            return Result.ok("评论成功");
        } catch (Exception e) {
            throw new MyException("评论失败");
        }
    }

    @Override
    public Result addGoodCount(Integer id, String token) {
        try {
            MComment mComment = mCommentMapper.selectById(id);
            Integer goodcount = mComment.getGoodcount();
            mComment.setGoodcount(goodcount + 1);
            mCommentMapper.updateById(mComment);
            mLogService.insertLog("用户对评价点赞", AboutMusic.NOTHINGABOUTMUSIC, id, LogDoType.INSERT, token);
            return Result.ok("点赞成功");
        } catch (Exception e) {
            throw new MyException("点赞失败");
        }
    }
}
